<template>
  <div class="app-content">
    <el-form class="crud-search-form" inline v-permissions="['system:user:query']">
      <el-form-item label="用户账号">
        <el-input placeholder="请输入用户账号" v-model="queryParams.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称">
        <el-input placeholder="请输入用户昵称" v-model="queryParams.nickname"></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input placeholder="请输入手机号码" v-model="queryParams.phone"></el-input>
      </el-form-item>
      <el-form-item>
        <ep-button plain svg-icon="Refresh" type="danger" @click="resetQuery">重置</ep-button>
        <ep-button plain svg-icon="Search" type="primary" @click="handleQuery">查询</ep-button>
      </el-form-item>
    </el-form>

    <div class="flex items-center mb-16px">
      <ep-button type="primary" plain svg-icon="Plus" @click="handleCreate()" v-permissions="['system:user:create']">新增</ep-button>
    </div>

    <ep-table :loading :data="list" :columns show-overflow-tooltip class="crud-table">
      <template #status="{ row }">
        <el-tag v-if="row.status === 0" type="danger">停用</el-tag>
        <el-tag v-else-if="row.status === 1" type="primary">正常</el-tag>
      </template>
      <template #gender="{ row }">
        <el-tag v-if="row.gender === 0" type="danger">未知</el-tag>
        <el-tag v-else-if="row.gender === 1" type="primary">男性</el-tag>
        <el-tag v-else-if="row.gender === 2" type="danger">女性</el-tag>
      </template>
      <template #operation="{ row }">
        <el-link type="primary" @click="handleUpdate(row.id)" v-permissions="['system:user:update']">编辑</el-link>
        <el-divider direction="vertical" v-permissions="['system:user:update']" />
        <el-link type="danger" @click="handleDelete(row)" v-permissions="['system:user:delete']">删除</el-link>
        <el-divider direction="vertical" v-permissions="['system:user:delete']" />
        <el-dropdown v-permissions="['system:user:update']">
          <div class="flex-center c-primary">
            <el-link type="primary">更多</el-link>
            <SvgIcon name="DArrowRight" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="resetPassword(row)">重置密码</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </ep-table>

    <EpPagination :total v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 用户新增、编辑对话框 -->
    <UserActionDialog ref="userActionDialogRef" @getList="getList" />
  </div>
</template>

<script setup lang="ts">
import { TipModal } from '@/utils'
import { UserRequest } from '@/api/system/user.request'
import UserActionDialog from './UserActionDialog.vue'

/** 用户新增、编辑对话框的组件实例对象 */
const userActionDialogRef = ref<InstanceType<typeof UserActionDialog>>()

/** 表格数据的加载状态 */
const loading = ref<boolean>(false)

/** 表格数据的总条目数 */
const total = ref<number>(0)

/** 表格数据 */
const list = ref<UserType.Entity[]>([])

/** 分页参数 */
const queryParams = ref({ pageNo: 1, pageSize: 10 } as TableQueryParams<UserType.Entity>)

/** 表格展示配置项 */
const columns: TableColumnProp<UserType.Entity>[] = [
  { align: 'center', label: '序号', type: 'index', minWidth: 80 },
  { align: 'center', label: '账号', prop: 'username', minWidth: 140 },
  { align: 'center', label: '真实姓名', prop: 'realname', minWidth: 100 },
  { align: 'center', label: '昵称', prop: 'nickname', minWidth: 140 },
  { align: 'center', label: '用户状态', slot: 'status', minWidth: 80 },
  { align: 'center', label: '性别', slot: 'gender', minWidth: 80 },
  { align: 'center', label: '手机号码', prop: 'phone', minWidth: 120 },
  { align: 'center', label: '创建时间', prop: 'createTime', minWidth: 170 },
  { align: 'center', label: '最近更新', prop: 'updateTime', minWidth: 170 },
  { align: 'center', label: '更新人', prop: 'updateBy', minWidth: 90 },
  { align: 'center', label: '操作', slot: 'operation', minWidth: 170, fixed: 'right' },
]

/** 向服务端查询列表数据 */
async function getList() {
  try {
    loading.value = true
    const data = await UserRequest.findList(queryParams.value)
    total.value = data.total
    list.value = data.records
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  const keys = Object.keys(queryParams.value).filter((key) => key !== 'pageSize')
  keys.forEach((key) => Reflect.deleteProperty(queryParams.value, key))
  handleQuery()
}

/** 新增 */
function handleCreate() {
  userActionDialogRef.value?.open()
}

/** 编辑 */
function handleUpdate(userId: string) {
  userActionDialogRef.value?.open(userId)
}

/** 删除 */
async function handleDelete(row: UserType.Entity) {
  try {
    const { cancel } = await TipModal.confirm(`确定要删除 ${row.realname} 吗？`)
    if (cancel) return TipModal.msg(`操作取消`)
    await UserRequest.delete({ userIds: row.id })
    if (list.value.length <= 1) queryParams.value.pageNo = queryParams.value.pageNo! > 1 ? queryParams.value.pageNo! - 1 : 1
    getList()
    TipModal.msgSuccess(`删除成功`)
  } catch (error: any) {
    console.error('删除用户失败: ', error.message || error)
  }
}

/** 重置用户密码为系统默认值 */
async function resetPassword(record: UserType.Entity) {
  try {
    const { cancel } = await TipModal.confirm(`确定要重置 ${record.realname} 的密码吗？`)
    if (cancel) return TipModal.msg(`操作取消`)
    const msg = await UserRequest.resetPassword({ userId: record.id })
    getList()
    TipModal.msgSuccess(`${msg || '重置操作成功'} `)
  } catch (error: any) {
    console.error('重置用户密码失败: ', error.message || error)
  }
}

getList()
</script>

<style lang="scss" scoped>
/* 表单顶部的搜索框 */
.crud-search-form {
  --search-form-item-width: 160px;
  .el-input {
    --el-input-width: var(--search-form-item-width);
  }
  .el-select {
    --el-select-width: var(--search-form-item-width);
  }
  .el-button {
    width: 81px;
  }
}
</style>
